/*
 * Copyright (c) 2010, Oracle. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of Oracle nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/* 
 * SIPNodesManagementFrame.java
 *
 * Create on Mar 29, 2014 10:53:49 PM
 *
 * Copyright (c) 2014 Zhiyong's Design Studio.
 *
 * This software contains confidential proprietary information belonging
 * to Zhiyong's Design Studio. No part of this information may be used, reproduced, 
 * or stored without prior written consent of Zhiyong's Design Studio.
 *
 */
package com.zhiyongstudio.contactorbook;

import com.zhiyongstudio.contactorbook.datamodel.ProjectDataModel;
import com.zhiyongstudio.contactorbook.datamodel.ProjectDataNode;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ProgressMonitor;

public class SIPNodesManagementFrame extends javax.swing.JFrame {

    private String filePath;
    private File selectedFile;
    private Scanner scanner;
    private String oldFilePath;
    private String fileProlog;
    private ProjectDataModel dataModel;
    private ProgressMonitor progressMonitor;

    /**
     * Creates new form Antenna
     */
    public SIPNodesManagementFrame() {
        initComponents();
        this.setIconImage(new ImageIcon(getClass().getResource("/com/zhiyongstudio/contactorbook/icons/application_edit.png")).getImage());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField_userName = new javax.swing.JTextField();
        jTextField_passWord = new javax.swing.JTextField();
        jButton_ClearInput = new javax.swing.JButton();
        jButton_SaveInput = new javax.swing.JButton();
        jButton_FindInput = new javax.swing.JButton();
        jButton_DeleteACallee = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea_FileContent = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jTextField3 = new javax.swing.JTextField();
        jButton_SelectFile = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jTextField_startNumber = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField_endNumber = new javax.swing.JTextField();
        jButton_AutoMaker = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jTextField_autoPassWord = new javax.swing.JTextField();
        jButton_AutoMake_Save = new javax.swing.JButton();
        jButton_DeleteBatch = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jComboBox_userName_length = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jComboBox_passWord_length = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle"); // NOI18N
        setTitle(bundle.getString("SIPNodesManagementFrame.title")); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("SIPNodesManagementFrame.jPanel1.border.title"))); // NOI18N

        jLabel1.setText(bundle.getString("SIPNodesManagementFrame.jLabel1.text")); // NOI18N

        jLabel2.setText(bundle.getString("SIPNodesManagementFrame.jLabel2.text")); // NOI18N

        jTextField_userName.setText(bundle.getString("SIPNodesManagementFrame.jTextField_userName.text")); // NOI18N
        jTextField_userName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_userNameActionPerformed(evt);
            }
        });

        jButton_ClearInput.setText(bundle.getString("SIPNodesManagementFrame.jButton_ClearInput.text")); // NOI18N
        jButton_ClearInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_ClearInputActionPerformed(evt);
            }
        });

        jButton_SaveInput.setText(bundle.getString("SIPNodesManagementFrame.jButton_SaveInput.text")); // NOI18N
        jButton_SaveInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SaveInputActionPerformed(evt);
            }
        });

        jButton_FindInput.setText(bundle.getString("SIPNodesManagementFrame.jButton_FindInput.text")); // NOI18N
        jButton_FindInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_FindInputActionPerformed(evt);
            }
        });

        jButton_DeleteACallee.setText(bundle.getString("SIPNodesManagementFrame.jButton_DeleteACallee.text")); // NOI18N
        jButton_DeleteACallee.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DeleteACalleeActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(jButton_FindInput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 60, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton_DeleteACallee)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton_ClearInput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton_SaveInput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 60, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextField_userName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jTextField_passWord, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)))
                .add(11, 11, 11))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jTextField_userName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2)
                    .add(jTextField_passWord, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton_FindInput)
                    .add(jButton_ClearInput)
                    .add(jButton_SaveInput)
                    .add(jButton_DeleteACallee))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("SIPNodesManagementFrame.jPanel2.border.title"))); // NOI18N

        jTextArea_FileContent.setColumns(20);
        jTextArea_FileContent.setRows(5);
        jScrollPane1.setViewportView(jTextArea_FileContent);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("SIPNodesManagementFrame.jPanel3.border.title"))); // NOI18N

        jButton_SelectFile.setText(bundle.getString("SIPNodesManagementFrame.jButton_SelectFile.text")); // NOI18N
        jButton_SelectFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SelectFileActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jTextField3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButton_SelectFile)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton_SelectFile))
                .add(0, 10, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("SIPNodesManagementFrame.jPanel4.border.title"))); // NOI18N

        jLabel3.setText(bundle.getString("SIPNodesManagementFrame.jLabel3.text")); // NOI18N

        jLabel4.setText(bundle.getString("SIPNodesManagementFrame.jLabel4.text")); // NOI18N

        jButton_AutoMaker.setText(bundle.getString("SIPNodesManagementFrame.jButton_AutoMaker.text")); // NOI18N
        jButton_AutoMaker.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AutoMakerActionPerformed(evt);
            }
        });

        jLabel7.setText(bundle.getString("SIPNodesManagementFrame.jLabel7.text")); // NOI18N

        jButton_AutoMake_Save.setText(bundle.getString("SIPNodesManagementFrame.jButton_AutoMake_Save.text")); // NOI18N
        jButton_AutoMake_Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AutoMake_SaveActionPerformed(evt);
            }
        });

        jButton_DeleteBatch.setText(bundle.getString("SIPNodesManagementFrame.jButton_DeleteBatch.text")); // NOI18N
        jButton_DeleteBatch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DeleteBatchActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel7)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jTextField_startNumber)
                    .add(jTextField_autoPassWord, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
                .add(18, 18, 18)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jTextField_endNumber, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 131, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel4Layout.createSequentialGroup()
                        .add(jButton_DeleteBatch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 64, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jButton_AutoMake_Save, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jButton_AutoMaker, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jTextField_startNumber, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4)
                    .add(jTextField_endNumber, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel4Layout.createSequentialGroup()
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jTextField_autoPassWord, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel7))
                        .addContainerGap(38, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(jButton_AutoMaker)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jButton_AutoMake_Save)
                            .add(jButton_DeleteBatch)))))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("SIPNodesManagementFrame.jPanel5.border.title"))); // NOI18N

        jLabel5.setText(bundle.getString("SIPNodesManagementFrame.jLabel5.text")); // NOI18N

        jComboBox_userName_length.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4", "5", "6", "7" }));
        jComboBox_userName_length.setSelectedIndex(1);

        jLabel6.setText(bundle.getString("SIPNodesManagementFrame.jLabel6.text")); // NOI18N

        jComboBox_passWord_length.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4", "5", "6", "7" }));
        jComboBox_passWord_length.setSelectedIndex(1);

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jComboBox_userName_length, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 69, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jLabel6)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jComboBox_passWord_length, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(jLabel5)
                .add(jComboBox_userName_length, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(jLabel6)
                .add(jComboBox_passWord_length, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.getAccessibleContext().setAccessibleName(bundle.getString("SIPNodesManagementFrame.jPanel2.AccessibleContext.accessibleName")); // NOI18N

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField_userNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_userNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField_userNameActionPerformed

    private void jButton_SelectFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SelectFileActionPerformed
        JFileChooser fc = new JFileChooser();
        int returnValue = fc.showOpenDialog(this);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            selectedFile = fc.getSelectedFile();
            oldFilePath = selectedFile.getPath();
            jTextField3.setText(oldFilePath);            //seting the text in the textfiled of file selector
            final ProgressBar pb = new ProgressBar();
            pb.setText("Loading file for initialization...");
            pb.setVisible(true);

            new Thread(new Runnable() {
                public void run() {
                    loadFile2TextArea(selectedFile);
                    scanner.reset();
                    fileProlog = getFileProlog(selectedFile);
                    dataModel = new ProjectDataModel(selectedFile);
                    pb.dispose();
                }
            }).start();

        } else {
            //do nothing.
        }
    }//GEN-LAST:event_jButton_SelectFileActionPerformed

    private void jButton_SaveInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SaveInputActionPerformed
        String userName = jTextField_userName.getText();
        String passWord = jTextField_passWord.getText();

        int userNameNrLength = Integer.parseInt((String) jComboBox_userName_length.getSelectedItem());
        int passWordLength = Integer.parseInt((String) jComboBox_passWord_length.getSelectedItem());

        if (userName.length() > userNameNrLength || passWord.length() > passWordLength) {
            JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("INPUT_LENGTH_VALID"));
        } else {
            saveCallee(userName, passWord);
        }
    }//GEN-LAST:event_jButton_SaveInputActionPerformed

    private void jButton_ClearInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ClearInputActionPerformed
        clearInput();
    }//GEN-LAST:event_jButton_ClearInputActionPerformed

    private void jButton_FindInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_FindInputActionPerformed
        Find findFrame = Find.getInstance(this);
        findFrame.setVisible(true);
    }//GEN-LAST:event_jButton_FindInputActionPerformed

    private void jButton_AutoMakerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AutoMakerActionPerformed
        autoMakeList();
    }//GEN-LAST:event_jButton_AutoMakerActionPerformed

    private void jButton_AutoMake_SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AutoMake_SaveActionPerformed
        saveToDisk();
    }//GEN-LAST:event_jButton_AutoMake_SaveActionPerformed

    private void jButton_DeleteACalleeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DeleteACalleeActionPerformed
        String userName = jTextField_userName.getText();
        if (!userName.isEmpty()) {
            if (dataModel != null) {
                int delIndex = dataModel.findCallee(userName);
                if (delIndex != -1) {
                    dataModel.deleteCallee(delIndex);
                    updateTextArea();
                    saveToDisk();
                } else {
                    JOptionPane.showMessageDialog(this, "There is no node with user name:" + userName);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Please load the conf file first!");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Please input the userName to delete!");
        }
    }//GEN-LAST:event_jButton_DeleteACalleeActionPerformed

    private void jButton_DeleteBatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DeleteBatchActionPerformed
        String startNumber = jTextField_startNumber.getText();
        String endNumber = jTextField_endNumber.getText();
        if (!startNumber.isEmpty()) {
            if (!endNumber.isEmpty()) {
//                int start = dataModel.findCallee(startNumber);
//                int end = dataModel.findCallee(endNumber);
                int start = Integer.parseInt(startNumber);
                int end = Integer.parseInt(endNumber);
                int foundIndex = -1;
                for (int i = start; i <= end; i++) {
                    foundIndex = dataModel.findCallee(getUserNameNr(i, jComboBox_userName_length.getSelectedIndex()));
                    if (foundIndex != -1) {
                        dataModel.deleteCallee(foundIndex);
                    }
                }
                updateTextArea();
                saveToDisk();
            } else {
                JOptionPane.showMessageDialog(this, "Please input the end number!");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Please input the start number!");
        }

    }//GEN-LAST:event_jButton_DeleteBatchActionPerformed

    private void saveToDisk() {
        if (dataModel != null) {
            final ProgressBar pb = new ProgressBar();
            pb.setVisible(true);
            new Thread(new Runnable() {

                public void run() {
                    writeToFile(fileProlog, dataModel, selectedFile);
                    pb.dispose();
                }
            }).start();
        } else {
            JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("RELOAD_CONF"));
        }
    }

    public void findCallee(String findUserName) {
        String findInput = findUserName;
        if (!findInput.isEmpty()) {
            if (dataModel != null) {
                int i = dataModel.findCallee(findInput);
                System.out.println(i);
                if (i != -1) {
                    jTextField_userName.setText(((ProjectDataNode) dataModel.getLinkedList().get(i)).getCallNr());
                    jTextField_passWord.setText(((ProjectDataNode) dataModel.getLinkedList().get(i)).getPassWord());
                }
            } else {
                JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("RELOAD_CONF"));
            }
        } else {
            JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("NO_USERNAME_FOUND"));

        }
    }

    private void autoMakeList() {
        String startNrString = jTextField_startNumber.getText();
        String endNrString = jTextField_endNumber.getText();
        String passWord = jTextField_passWord.getText();
        int userNameNrLength = Integer.parseInt((String) jComboBox_userName_length.getSelectedItem());
        int passWordLength = Integer.parseInt((String) jComboBox_passWord_length.getSelectedItem());

        if (startNrString.length() > userNameNrLength || endNrString.length() > userNameNrLength || passWord.length() > passWordLength) {
            JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("INPUT_LENGTH_VALID"));
        } else {
            if (startNrString.isEmpty() || endNrString.isEmpty()) {
                JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("START_END_EMPTY"));
            } else {
                if (dataModel != null) {

                    final ProgressBar pb = new ProgressBar();
                    pb.setText(java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("MAKING_LIST"));
                    pb.setVisible(true);

                    final String startNrString_t = startNrString;
                    final String endNrString_t = endNrString;
                    final int userNameNrLength_t = userNameNrLength;
                    final String passWord_t = passWord;

                    new Thread(new Runnable() {

                        public void run() {
                            for (int i = Integer.parseInt(startNrString_t); i <= Integer.parseInt(endNrString_t); i++) {
                                updateDataModel(getUserNameNr(i, userNameNrLength_t), passWord_t);
                            }

                            dataModel.sortCalleeList();
                            //Write infomation to text area.        
                            String userName;
                            String passWordToDisp;
                            jTextArea_FileContent.setText("");
                            jTextArea_FileContent.append(fileProlog);
                            for (int i = 0; i < dataModel.getSize(); i++) {
                                userName = "[" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getCallNr() + "]" + "\n";
                                jTextArea_FileContent.append(userName);
                                passWordToDisp = "password=" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getPassWord() + "\n\n";
                                jTextArea_FileContent.append(passWordToDisp);
                            }
                            pb.dispose();
                        }
                    }).start();

                } else {
                    JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("RELOAD_CONF"));
                }
            }
        }

    }

    private void updateDataModel(String userNameNr, String passWord) {
        if (dataModel != null) {
            if (!userNameNr.isEmpty()) {
                dataModel.addCallee(new ProjectDataNode(userNameNr, passWord));
            }
        } else {
            JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("RELOAD_CONF"));
        }
    }

    /**
     *
     * @param userNameNr
     * @param length
     * @return
     */
    private String getUserNameNr(int userNameNr, int length) {
        String userName = "";
        int zeroNr = length - Integer.toString(userNameNr).length();
        for (int i = 0; i < zeroNr; i++) {
            userName += "0";
        }
        userName += Integer.toString(userNameNr);
        return userName;
    }

    private void loadFile2TextArea(File file) {
        jTextArea_FileContent.setText("");
        try {
            scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                jTextArea_FileContent.append(scanner.nextLine());
                if (!scanner.hasNext("\n")) {
                    jTextArea_FileContent.append("\n");
                }
            }
            scanner.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void clearInput() {
        jTextField_userName.setText("");
        jTextField_passWord.setText("");
    }

    private void backupFile(File oldFile) {
        Path source = Paths.get(oldFile.getPath());
        Path target = Paths.get(oldFile.getPath() + ".bak");
        try {
            Files.copy(source, target, REPLACE_EXISTING);
        } catch (IOException ex) {
            Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String getFileProlog(File selectedFile) {
        String rawFileProlog = "";
        String line;
        try {
            scanner = new Scanner(selectedFile);
            while (scanner.hasNextLine()) {
                line = scanner.nextLine();
                if (line.contains("[center]")) {
                    break;
                }
                rawFileProlog += line;
                if (!scanner.hasNext("\n")) {
                    rawFileProlog += "\n";
                }
            }
            scanner.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rawFileProlog;
    }

    /**
     * The method is used to put the callee into the datamodel and save it to
     * the file and display in the contents panel.
     *
     * @param userName String user name
     * @param passWord String password
     */
    private void saveCallee(String userName, String passWord) {
        if (dataModel != null) {
            if (!userName.isEmpty()) {
                dataModel.addCallee(new ProjectDataNode(userName, passWord));
                dataModel.sortCalleeList();
//                jTextArea_FileContent.setText("");
//                jTextArea_FileContent.append(fileProlog);
//                for (int i = 0; i < dataModel.getSize(); i++) {
//                    jTextArea_FileContent.append("[" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getCallNr() + "]" + "\n");
//                    jTextArea_FileContent.append("password=" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getPassWord() + "\n\n");
//                }
//                writeToFile(fileProlog, dataModel, selectedFile);
                updateTextArea();
                saveToDisk();
            } else {
                JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("USERNAME_EMPTY"));
            }
        } else {
            JOptionPane.showMessageDialog(this, java.util.ResourceBundle.getBundle("com/zhiyongstudio/contactorbook/Bundle").getString("RELOAD_CONF"));
        }

    }

    private void updateTextArea() {
        jTextArea_FileContent.setText("");
        jTextArea_FileContent.append(fileProlog);
        for (int i = 0; i < dataModel.getSize(); i++) {
            jTextArea_FileContent.append("[" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getCallNr() + "]" + "\n");
            jTextArea_FileContent.append("password=" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getPassWord() + "\n\n");
        }
    }

    private void writeToFile(String fileProlog, ProjectDataModel dataModel, final File selectedFile) {
        backupFile(selectedFile);
        String stringToFile = fileProlog;
        String userName;
        String passWord;
        for (int i = 0; i < dataModel.getSize(); i++) {
            userName = "[" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getCallNr() + "]" + "\n";
            stringToFile += userName;
            passWord = "password=" + ((ProjectDataNode) dataModel.getLinkedList().get(i)).getPassWord() + "\n\n";
            stringToFile += passWord;
        }

        final String contentsToFile = stringToFile;

        updateFile(selectedFile, contentsToFile);

    }

    private void updateFile(File selectedFile, String stringToFile) {
        synchronized (selectedFile) {
            FileWriter fw;
            try {
                fw = new FileWriter(selectedFile.getPath());
                fw.write(stringToFile);
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.LookAndFeelInfo[] installedLookAndFeels = javax.swing.UIManager.getInstalledLookAndFeels();
            for (int idx = 0; idx < installedLookAndFeels.length; idx++) {
                if ("Nimbus".equals(installedLookAndFeels[idx].getName())) {
                    javax.swing.UIManager.setLookAndFeel(installedLookAndFeels[idx].getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SIPNodesManagementFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SIPNodesManagementFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_AutoMake_Save;
    private javax.swing.JButton jButton_AutoMaker;
    private javax.swing.JButton jButton_ClearInput;
    private javax.swing.JButton jButton_DeleteACallee;
    private javax.swing.JButton jButton_DeleteBatch;
    private javax.swing.JButton jButton_FindInput;
    private javax.swing.JButton jButton_SaveInput;
    private javax.swing.JButton jButton_SelectFile;
    private javax.swing.JComboBox jComboBox_passWord_length;
    private javax.swing.JComboBox jComboBox_userName_length;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea_FileContent;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField_autoPassWord;
    private javax.swing.JTextField jTextField_endNumber;
    private javax.swing.JTextField jTextField_passWord;
    private javax.swing.JTextField jTextField_startNumber;
    private javax.swing.JTextField jTextField_userName;
    // End of variables declaration//GEN-END:variables

}
